<?php

namespace App\Http\Controllers\Api;


use App\Library\OSS;
use App\Modules\Comment\Jobs\CheckJob;
use App\Modules\Comment\Models\Comment;
use App\Modules\Crowd\Manager;
use App\Modules\Crowd\Models\Crowd;
use App\Modules\Crowd\Models\CrowdGood;
use App\Modules\Order\Models\Order;
use App\Modules\Order\Models\SupportOrder;
use App\Modules\Payment\Models\WeChatPay;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class CrowdController extends ApiController
{
    public function getList(Request $request)
    {
        $this->validate($request, [
            'offset' => "nullable|integer",
            'count' => "nullable|integer"
        ]);
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $user = $this->getUser();
        $re = Crowd::query()
            ->where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($count)
            ->get();
        return $this->success($re);
    }

    public function createCrowd(Request $request)
    {
        $id = $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        $goods = CrowdGood::query()->find($id);
        $cover = [];
        foreach ($goods->cover as $value) {
            $cover[] = OSS::instance()->getUrl($value);
        }

        $crowd = Crowd::query()
            ->create([
                'no' => Crowd::getNo(),
//                'shop_id' => $goods->shop_id,
                'user_id' => $user->id,
                'number' => 1,
                'support_money' => 0,
                'self_pay' => 0,
                'cover' => $cover[0]??'',
                'title' => $goods->name,
                'link_id' => $goods->id,
                'detail' => [
                    'id' => $goods->id,
                    'name' => $goods->name,
                ],
                'price' => $goods->price,
                'status' => Crowd::STATUS_PROGRESSION,
            ]);;
        return $this->success([
            'id' => $crowd->id,
        ]);
    }
    public function support(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
            'money' => "required|integer",
            'content' => "nullable|string"
        ]);
        $id = $request->input('id');
        $money = $request->input('money');
        $content = $request->input('content');
        $user = $this->getUser();
        if ($money < 1) {
            return $this->fail('支持金额错误');
        }
        /** @var Crowd $crowd */
        $crowd = Crowd::query()
            ->where('id', $id)
            ->where('status', Crowd::STATUS_PROGRESSION)
            ->first();
        if (is_null($crowd)) {
            return $this->fail('众筹已经停止');
        }
        $order = Manager::support($user, $crowd, $money, $content);
        $params = WeChatPay::getParameters($order->getType(), $order->pay_no, "支持", $order->getPrice(), $user, 1);
        return $this->success([
            'id' => $order->id,
            'params' => $params,
        ]);
    }

    public function detail(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|string',
        ]);
        $id = $request->input('id');
        $crowd = Crowd::query()
            ->where('id', $id)
            ->first();
        $user = User::query()->find($crowd->user_id);
        $crowdUser = User::query()
            ->find($crowd->user_id);
        if (is_null($crowd)) {
            return $this->fail('id错误');
        }
        $support = SupportOrder::query()
            ->where('crowd_id', $crowd->id)
            ->where('status', SupportOrder::STATUS_SUCCESS)
            ->count();
        $crowd->nickname = $user->nickname;
        $crowd->avatar = $user->avatar;
        $crowd->number = $support;
        $crowd->nickname = $crowdUser->nickname;
        $crowd->avatar = $crowdUser->avatar;
        return $this->success($crowd);
    }

    public function getSupport(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
            'offset' => "integer",
            'count' => "integer",
        ]);
        $id = $request->input('id');
        $offset = $request->input('offset');
        $count = $request->input('count');
        $crowd = Crowd::query()->where('id', $id)->first();
        if (is_null($crowd)) {
            return $this->fail('编号错误');
        }
        $support = SupportOrder::query()
            ->where('crowd_id', $crowd->id)
            ->where('status', SupportOrder::STATUS_SUCCESS)
            ->orderBy("created_at", 'desc')
            ->offset($offset)
            ->limit($count)
            ->get();
        $user = User::query()
            ->whereIn('id', $support->pluck('user_id')->all())
            ->get()
            ->keyBy('id');
        $re = $support->map(function ($item) use($user) {
            return [
                'nickname' => $user->get($item->user_id)->nickname,
                'avatar' => $user->get($item->user_id)->avatar,
                'money' => $item->price,
                'content' => $item->content,
                'created_at' => $item->created_at,
            ];
        });
        return $this->success($re);
    }

    public function getGoods(Request $request)
    {
        $this->validate($request, [
            'offset' => 'integer',
            'count' => 'integer',
        ]);
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $re = CrowdGood::query()
            ->where('status', CrowdGood::STATUS_ON)
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($count)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'cover' => OSS::instance()->getUrl($item->cover),
                    'price' => $item->price,
                    'description' => $item->description,
                    'status' => $item->status,
                ];
            });

        return $this->success($re);
    }
    public function getGoodDetail(Request $request)
    {
//        $this->validate($request, [
//            'id' => 'required|integer',
//        ]);
//        $id = $request->input('id');
        $re = CrowdGood::query()->where('status', CrowdGood::STATUS_ON)->first();
        if (is_null($re)) {
            return $this->success([]);
        }
        $cover = [];
        foreach ($re->cover as $value) {
            $cover[] = OSS::instance()->getUrl($value);
        }
        $re->cover = $cover;
        return $this->success($re);
    }

    public function getCommentCount(Request $request)
    {
//        $this->validate($request, [
//            'id' => 'required|integer',
//        ]);
//        $id = $request->input('id');
        $count = Comment::query()
            ->where('type', Comment::TYPE_CROWD)
//            ->where('link_id', $id)
            ->where('is_show', 1)
            ->selectRaw('count(1) as count, count(if(score > 3, 1, null)) as favorable')
            ->first();
        return $this->success($count);
    }

    public function getSupportStatus(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $support = SupportOrder::query()
            ->where('id', $id)
            ->where('status', SupportOrder::STATUS_SUCCESS)
            ->first();
        return $this->success($support->status);
    }

    public function comment(Request $request)
    {
        $this->validate($request, [
            'crowd_id' => 'required|integer',
            'score' => 'required|integer',
            'content' => 'string',
            'image' => 'array',
        ]);
        $user = $this->getUser();
        $crowdId = $request->input('crowd_id');
        $content = $request->input('content');
        $image = $request->input('image');
        $score = $request->input('score');

        if (!empty($content)) {
            $app = EasyWeChat::miniProgram();
            $result = $app->content_security->checkText($content);
            if ($result['errcode'] != 0) {
                return $this->fail("发布内容包含敏感词");
            }
        }

        $crowd = Crowd::query()
            ->where('id', $crowdId)
            ->where('user_id', $user->id)
            ->where('status', Order::STATUS_PAID)
            ->first();
        if (!is_null($crowd)) {
            return $this->fail('为众筹成功,不能评论');
        }

        $comment = Comment::query()
            ->create([
                'user_id' => $user->id,
                'link_id' => $crowd->link_id,
                'score' => $score,
                'type' => Comment::TYPE_CROWD,
                'content' => $content,
                'image' => $image,
                'is_checked' => 0,
                'is_show' => 0,
            ]);
        dispatch(new CheckJob($content));
        return $this->success();
    }

    public function getComments(Request $request)
    {
        $this->validate($request, [
//            'id' => 'required|integer',
            'offset' => 'integer',
            'count' => 'integer',
        ]);
//        $id = $request->input('id');
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);

        $comment = Comment::query()
            ->where('type', Comment::TYPE_CROWD)
//            ->where('link_id', $id)
            ->where('is_show', 1)
            ->orderBy('created_at')
            ->offset($offset)
            ->limit($count)
            ->get();
        $user = User::query()
            ->whereIn('user_id', $comment->pluck('user_id')->all())
            ->get()
            ->keyBy('id');
        $re = $comment->map(function ($item) use($user) {
            if (!empty($item->image)) {
                $tmp = [];
                foreach ($item->image as $value) {
                    $tmp[] = OSS::instance()->get($value);
                }
                $item->image = $tmp;
            }
            return [
                'id' => $item->id,
                'nickname' => $user->get($item->user_id)->nickname,
                'avatar' => $user->get($item->user_id)->avatar,
                'content' => $item->content,
                'image' => $item->image,
                'created_at' => $item->created_at,
            ];
        });
        return $this->success($re);
    }
}
